package com.qbadroid;

import java.util.Arrays;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AudioActivity extends Activity implements Runnable {

	private static final String TAG = "REC";
	private Button recordButton;
	private ProgressBar progressBar;
	private TextView bufferText;
	
	private AudioRecord recorder;
	private AudioListener listener;
	
	private int buffer;
	private boolean isRecording;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int value = msg.arg1;
			progressBar.setProgress(value);
			bufferText.setText(""+value);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.audio);
		
		recordButton = (Button)findViewById(R.id.recordButton);
		progressBar = (ProgressBar)findViewById(R.id.progressBar);
		bufferText = (TextView)findViewById(R.id.bufferText);
		
		listener = new AudioListener();
		
		recordButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				runAudioRecord();
			}
		});
		
		isRecording = true;
		
		recorder = getAudioRecord();
		if(recorder == null){
			Log.i(TAG, "Recorder Error");
			finish();
		}
	}
	
	private AudioRecord getAudioRecord(){
		for(int sample: new int[]{8000, 11025, 22050, 4410}){
			int bufferSize = AudioRecord.getMinBufferSize(sample, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
			if(bufferSize > 0){
				buffer = bufferSize;
				AudioRecord recorder = new AudioRecord(AudioSource.MIC, sample, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
				
				if(recorder.getState() == AudioRecord.STATE_INITIALIZED)
					return recorder;
			}
		}
		return null;
	}
	
	private void runAudioRecord(){
		Thread thread = new Thread(this);
		thread.start();
	}
	
	@Override
	public void run() {
		
		recorder.setPositionNotificationPeriod(1000);
		recorder.setRecordPositionUpdateListener(listener);
		
		while(isRecording){
			recorder.startRecording();

			byte[] data = new byte[buffer];
			recorder.read(data, 0, buffer);
			
			Arrays.sort(data);
			Message msg = handler.obtainMessage();
			msg.arg1 = (int)data[buffer-1];
			handler.sendMessage(msg);
			Log.i(TAG, ""+data.length);
		}
	}
	
	@Override
	protected void onPause() {
		isRecording = false;
		if(recorder != null){
			recorder.release();
			recorder = null;
		}
		super.onPause();
	}

}
